<template>
  <div class="sales-order-container">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form layout="inline" :model="queryParams" @finish="handleQuery" class="search-form">
        <a-form-item label="销售单号" name="salesOrderNo">
          <a-input v-model:value="queryParams.salesOrderNo" placeholder="请输入销售单号" />
        </a-form-item>
        <a-form-item label="客户" name="customerId">
          <a-select
            v-model:value="queryParams.customerId"
            placeholder="请选择客户"
            style="width: 200px"
            allow-clear
            show-search
            option-filter-prop="label"
          >
            <a-select-option
              v-for="customer in customerList"
              :key="customer.customerId"
              :value="customer.customerId"
              :label="customer.customerName"
            >
              {{ customer.customerName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="queryParams.status" placeholder="请选择状态" style="width: 120px" allow-clear>
            <a-select-option v-for="item in salesOrderStatusOptions" :key="item.value" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">
              <template #icon><search-outlined /></template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon><redo-outlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 操作按钮 -->
      <div class="table-operations">
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <template #icon><plus-outlined /></template>
            新增
          </a-button>
          <a-button type="primary" danger :disabled="!selectedRowKeys.length" @click="handleBatchDelete">
            <template #icon><delete-outlined /></template>
            批量删除
          </a-button>
        </a-space>
      </div>

      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data-source="salesOrderList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :row-key="(record: SalesOrder) => record.salesOrderId"
        @change="handleTableChange"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ record.statusDesc || getStatusLabel(record.status) }}
            </a-tag>
          </template>

          <!-- 销售额列 -->
          <template v-if="column.key === 'salesAmount'">
            ¥{{ Number(record.salesAmount || 0).toFixed(2) }}
          </template>

          <!-- 操作列 -->
          <template v-if="column.key === 'operation'">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这个销售订单吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a class="danger-text">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 销售订单表单对话框 -->
    <sales-order-form
      v-model:visible="formVisible"
      :form-data="formData"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import type { SalesOrder, SalesOrderSearch } from '@/types/sales-order'
import { salesOrderStatusOptions, SalesOrderStatus } from '@/types/sales-order'
import type { Customer } from '@/types/customer'
import type { TableProps } from 'ant-design-vue'
import * as salesOrderApi from '@/api/sales-order'
import * as customerApi from '@/api/customer'

// 引入子组件
import SalesOrderForm from './components/SalesOrderForm.vue'

// 销售订单状态
const loading = ref(false)
const salesOrderList = ref<SalesOrder[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

// 客户列表
const customerList = ref<Customer[]>([])

// 查询参数
const queryParams = reactive<SalesOrderSearch>({
  salesOrderNo: '',
  customerId: undefined,
  status: undefined
})

// 选中行数据
const selectedRowKeys = ref<(string | number)[]>([])

// 表单状态
const formVisible = ref(false)
const formData = ref<Partial<SalesOrder>>({})

// 表格列定义
const columns = [
  {
    title: '销售单号',
    dataIndex: 'salesOrderNo',
    key: 'salesOrderNo'
  },
  {
    title: '销售人员',
    dataIndex: 'salespersonName',
    key: 'salespersonName'
  },
  {
    title: '客户',
    dataIndex: 'customerName',
    key: 'customerName'
  },
  {
    title: '销售额',
    dataIndex: 'salesAmount',
    key: 'salesAmount'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    sorter: true
  },
  {
    title: '操作',
    key: 'operation',
    width: 150
  }
]

// 获取状态标签
const getStatusLabel = (status: number) => {
  const option = salesOrderStatusOptions.find(item => item.value === status)
  return option?.label || '未知'
}

// 获取状态颜色
const getStatusColor = (status: number) => {
  switch (status) {
    case SalesOrderStatus.COMPLETED: return 'green'
    case SalesOrderStatus.REFUNDED: return 'red'
    default: return 'default'
  }
}

// 初始化加载数据
onMounted(() => {
  getList()
  loadCustomerList()
})

// 加载客户列表
const loadCustomerList = async () => {
  try {
    const customers = await customerApi.getCustomerList()
    customerList.value = customers || []
  } catch (error) {
    console.error('加载客户列表失败:', error)
  }
}

// 获取销售订单列表
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams,
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    }

    const res = await salesOrderApi.getSalesOrderPage(params)
    salesOrderList.value = res.rows || []
    pagination.total = res.total || 0
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.current = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  Object.keys(queryParams).forEach(key => {
    // @ts-ignore
    queryParams[key] = key === 'customerId' || key === 'status' ? undefined : ''
  })
  pagination.current = 1
  getList()
}

// 表格变化处理
const handleTableChange: TableProps['onChange'] = (pag, filters, sorter) => {
  pagination.current = pag.current as number
  pagination.pageSize = pag.pageSize as number
  getList()
}

// 选择行变化
const onSelectChange = (keys: (string | number)[]) => {
  selectedRowKeys.value = keys
}

// 新增销售订单
const handleAdd = () => {
  formData.value = {}
  formVisible.value = true
}

// 编辑销售订单
const handleEdit = async (record: SalesOrder) => {
  try {
    const salesOrderDetail = await salesOrderApi.getSalesOrderDetail(record.salesOrderId)
    formData.value = { ...salesOrderDetail }
    formVisible.value = true
  } catch (error) {
    message.error('获取销售订单详情失败')
    console.error('获取销售订单详情失败:', error)
  }
}

// 删除销售订单
const handleDelete = async (record: SalesOrder) => {
  try {
    await salesOrderApi.deleteSalesOrder(record.salesOrderId)
    message.success('删除成功')
    if (pagination.current === 1) {
      getList()
    } else {
      pagination.current = 1
      getList()
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRowKeys.value.length) {
    message.warning('请至少选择一条记录')
    return
  }

  try {
    // 循环调用单个删除接口
    for (const salesOrderId of selectedRowKeys.value) {
      await salesOrderApi.deleteSalesOrder(salesOrderId as number)
    }
    message.success('批量删除成功')
    pagination.current = 1
    getList()
    selectedRowKeys.value = []
  } catch (error) {
    message.error('批量删除失败')
  }
}

// 表单提交成功回调
const handleSuccess = () => {
  formVisible.value = false
  getList()
}
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 16px;
}

.danger-text {
  color: #ff4d4f;
}

.danger-text:hover {
  color: #ff7875;
}
</style>

